<template>
  <div class="app-container">
    <div
      v-show="
        !detailInfo.visible &&
        !summaryDetailInfo.visible &&
        !purchOrderCheckApplicationInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
        >
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-batchGeneratePurchOrder>
            <el-button
              :disabled="!canBatchGenerate"
              @click="generatePurchOrder"
              >生成采购单
            </el-button>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :tab-index="true"
        :check-box="true"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
        <template v-slot:col-purchType="scope">
          {{ !!scope.row.purchType ? "申购单" : "申购汇总单" }}
        </template>
      </table-container>
    </div>
    <!-- 明细 -->
    <PurchApplicationDetail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :table-row="detailInfo.data"
      @returnBack="getList"
    />
    <PurchApplicationSummaryDetail
      v-if="summaryDetailInfo.visible"
      v-model:visible="summaryDetailInfo.visible"
      :table-row="summaryDetailInfo.data"
      @returnBack="getList"
    />
    <checkPurchApplication
      v-if="purchOrderCheckApplicationInfo.visible"
      v-model:visible="purchOrderCheckApplicationInfo.visible"
      :purchApplicationId="purchOrderCheckApplicationInfo.orderId"
      :purch-application-info="purchOrderCheckApplicationInfo.info"
      :purch-type="purchOrderCheckApplicationInfo.purchType"
      :purch-according="purchOrderCheckApplicationInfo.purchAccording"
      @returnModify="returnModify"
    />
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <page-dialog
      v-if="pageDialogInfo.visible"
      :title="pageDialogInfo.title"
      v-model:visible="pageDialogInfo.visible"
      :width="pageDialogInfo.width"
      :bt-loading="pageDialogInfo.btLoading"
      :bt-list="pageDialogInfo.btList"
      @reset="closeDialog"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="pageFormInfo.ref"
        :data="pageFormInfo.data"
        :field-list="pageFormInfo.fieldList"
        :label-width="pageFormInfo.labelWidth"
      />
    </page-dialog>
  </div>
</template>

<script setup name="pendPurchOrder">
import {
  postPendPurchApplicationPage,
  methodPurchApplication,
  applicationsSummaryValidatePurch,
  applicationsValidatePurch,
  applicationSummaryStop,
  stopPurchApplication,
  patchInsetFromApplication,
} from "@/api/purch";
import { getReceiveAddressAll } from "@/api/core";

import TableContainer from "@/components/TableContainer/index";
import SetPreference from "@/components/SetPreference/index";
import AdvancedSearch from "@/components/AdvancedSearch/index";
import PurchApplicationDetail from "@/views/purch/application/detail";
import checkPurchApplication from "@/views/purch/order/checkPurchApplication.vue";
import { getCustomizeSetting, updateUserCustomize } from "@/api/customize";
import PageDialog from "@/components/PageDialog/index";
import PageForm from "@/components/PageForm/index";
import PurchApplicationSummaryDetail from "@/views/purch/applicationSummary/detail";

const { proxy } = getCurrentInstance();
// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: "",
    queryMap: {},
    groupMap: {},
    groups: [],
    queryParams: {},
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: "button", label: "搜索", event: _search },
    { type: "button", label: "高级查询", event: _advancedSearchShow },
    { type: "button", label: "重置", event: _clearSearch },
  ],
  btnList: [
    // { value: "batchGeneratePurchOrder", type: "slot" }
  ],
});
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: "right",
    label: "操作",
    width: '130',
    btList: [
      {
        label: "生成采购单",
        event: generatePurchOrder,
        show: proxy.$permission("pendPurchOrder:generate"),
        ifRender: function (row) {
          return row.status === 5 || row.status === 3;
        },
      },
      {
        label: "中止",
        event: checkBreak,
        show: proxy.$permission("pendPurchOrder:stop"),
        ifRender: ifRenderStop,
      },
    ],
  },
});
//明细相关
const detailInfo = reactive({
  visible: false,
  title: "申购单明细",
  data: {},
});
const summaryDetailInfo = reactive({
  visible: false,
  title: "申购单汇总明细",
  data: {},
});
const purchOrderCheckApplicationInfo = reactive({
  visible: false,
  title: "通过申购单生成采购单",
  orderId: null,
  info: undefined,
  purchType: null,
});
const pageDialogInfo = ref({
  title: "选择采购依据",
  visible: false,
  type: "",
  width: "400px",
  row: {},
  btLoading: false,
  btList: [
    {
      label: "关闭",
      type: "",
      icon: "",
      event: closeDialog,
      show: true,
    },
    {
      label: "保存",
      type: "primary",
      icon: "",
      event: saveDialog,
      saveLoading: false,
      show: true,
    },
  ],
});
const pageFormInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: "采购依据",
      value: "purch_according",
      type: "select-model",
      code: "purch_according",
    },
  ],
});
const selectRow = ref({});
const tableKey = ref(
  "pendPurchOrderList-com.slip.spd.entity.vo.purch.ApplicationVO"
);
const detailListInfo = ref({
  visible: false,
});
const preferenceInfo = ref({
  visible: false,
});
const advancedSearchInfo = ref({
  visible: false,
  data: {},
});
const clearType = ref(true);
const slipSelectRequest = ref(true);
const canBatchGenerate = computed(() => {
  return (
    tableInfo.selections.filter(
      (item) => item.status === 5 || item.status === 3
    ).length !== 0 && proxy.$permission("pendPurchOrder:generate")
  );
});
let obj = {
  statusValue: {
    label: "状态",
    value: "statusValue",
    asValue: "status",
    componentType: "select-model",
    code: "purch_application_status",
    show: false,
    hidden: true,
  },
  mergeTypeValue: {
    label: "合并状态",
    value: "mergeTypeValue",
    asValue: "mergeType",
    componentType: "select-model",
    code: "merge_type",
    show: false,
    hidden: true,
  },
};
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
});
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
});
getCustomize();

function _search() {
  search();
}
function _advancedSearchShow() {
  advancedSearchShow();
}
function _clearSearch() {
  clearSearch();
}
function handleEvent(event, data) {
  switch (event) {
    case "tableCheck":
      tableInfo.selections = [...data];
      break;
  }
}
function clearSearch() {
  clearType.value = !clearType.value;
  advancedSearchInfo.value.data = {};
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap);
  search();
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true;
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value);
    }
  });
}
async function advancedSearchCallback(obj) {
  filterInfo.query.queryMap = {};
  filterInfo.query.queryDtoList = [...obj.queryDtoList];
  advancedSearchInfo.value.data = obj.data;
  await getList();
  clearType.value = !clearType.value;
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap);
}

function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem("storeRowId");
  if (rowId && row.id === Number(rowId)) {
    return "check-row";
  }
  return "";
}
function ifRenderStop(row) {
  if (row.purchType) {
    let type = false;
    if (row.status === 5) {
      type = true;
    } else if (row.status === 3) {
      if (row.beforeMergeStatus === 2) {
        type = true;
      } else {
        type = false;
      }
    }
    return type;
  } else {
    return (
      row.status === 5 ||
      (row.status === 3 &&
        proxy.$store.state.permission.systemConfig
          .allow_purch_application_approval === 1)
    );
  }
}
function returnModify() {
  if (purchOrderCheckApplicationInfo.purchApplicationId) {
    getList();
  } else {
    search();
  }
}
function showDetail(row) {
  sessionStorage.setItem("storeRowId", row.id);
  let purchType = row.purchType;
  if (purchType === 0) {
    detailInfo.visible = true;
    detailInfo.data = { ...row };
  } else if (purchType === 1) {
    summaryDetailInfo.visible = true;
    summaryDetailInfo.data = { ...row };
  }
}
//终止
function checkBreak(row) {
  const stopApi = row.purchType ? applicationSummaryStop : stopPurchApplication;
  stopApi([row.id]).then((res) => {
    if (res && res.success) {
      getList();
    }
  });
}
//生成采购单
function generatePurchOrder(row) {
  if (
    proxy.$store.state.permission.systemConfig.purch_according != "1" &&
    proxy.$store.state.permission.systemConfig.purch_according != "2"
  ) {
    pageDialogInfo.value.visible = true;
    selectRow.value = row;
  } else {
    const params = {
      isDefault: "1",
    };
    if (row && row.id) {
      const validateApi = row.purchType
        ? applicationsSummaryValidatePurch
        : applicationsValidatePurch;
      validateApi(row).then((resp) => {
        if (resp && resp.success) {
          getReceiveAddressAll(params).then((resp) => {
            if (resp && resp.success) {
              sessionStorage.setItem("storeRowId", row.id);
              purchOrderCheckApplicationInfo.visible = true;
              purchOrderCheckApplicationInfo.orderId = row.id;
              purchOrderCheckApplicationInfo.purchType = row.purchType;
              purchOrderCheckApplicationInfo.info = row;
            }
          });
        }
      });
    } else {
      //批量生成采购单
      getReceiveAddressAll(params).then((resp) => {
        if (resp && resp.success) {
          batchInsetFromApplication(
            proxy.$store.state.permission.systemConfig.purch_according
          );
        }
      });
    }
  }
  return;
}
function batchInsetFromApplication(purchAccording) {
  let arr = [];
  tableInfo.selections.forEach((item) => {
    arr.push({
      id: item.id,
      purchType: item.purchType,
      purchAccording: Number(purchAccording),
    });
  });
  patchInsetFromApplication(arr).then((resp) => {
    if (resp && resp.success) {
      getList();
    }
  });
}
function handelMethodRequest(row, method) {
  const ids = [row.id];
  methodPurchApplication(ids, method).then((resp) => {
    if (resp.success) {
      tableInfo.refresh = Math.random();
    }
  });
}
async function getList() {
  tableInfo.refresh = Math.random();
}
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {};
  filterInfo.query.queryDtoList = [];
  tableInfo.initCurpage = Math.random();
  tableInfo.refresh = Math.random();
}
function getCustomize() {
  let param = {
    tableKey: tableKey.value,
  };
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data;
      filterInfo.query.customizeUserVO = data;
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      );
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      );
      filterInfo.query.queryMap = {
        ...filterInfo.query.queryMap,
        ...searchInfo.queryMap,
      };
      filterInfo.searchList = searchInfo.searchList;
      filterInfo.searchList.forEach((item) => {
        item.event = search;
      });
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap);
      tableInfo.api = postPendPurchApplicationPage;
      getList();
    }
  });
}
function closeDialog() {
  pageDialogInfo.value.visible = false;
  pageFormInfo.value.data = {};
}
function saveDialog() {
  if (pageFormInfo.value.data.purch_according) {
    const params = {
      isDefault: "1",
    };
    if (selectRow.value && selectRow.value.id) {
      console.log(1111)
      const validateApi = selectRow.value.purchType
        ? applicationsSummaryValidatePurch
        : applicationsValidatePurch;
      validateApi(selectRow.value).then((resp) => {
        if (resp && resp.success) {
          getReceiveAddressAll(params).then((resp) => {
            if (resp && resp.success) {
              sessionStorage.setItem("storeRowId", selectRow.value.id);
              purchOrderCheckApplicationInfo.orderId = selectRow.value.id;
              purchOrderCheckApplicationInfo.info = selectRow.value;
              purchOrderCheckApplicationInfo.purchType =
                selectRow.value.purchType;
              purchOrderCheckApplicationInfo.purchAccording =
                pageFormInfo.value.data.purch_according;
              closeDialog();
              proxy.$nextTick(() => {
                purchOrderCheckApplicationInfo.visible = true;
              });
            }
          });
        }
      });
    } else {
      //批量生成采购单
      console.log(11112)
      getReceiveAddressAll(params).then((resp) => {
        if (resp && resp.success) {
          batchInsetFromApplication(
            pageFormInfo.value.data.purch_according
          );
          closeDialog();
        }
      });
    }
    return;
  } else {
    proxy.$message.warning("请选择采购依据");
  }
}
</script>

<style scoped></style>
